package cn.tedu.sp11.filter;

import cn.tedu.web.util.JsonResult;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

@Component
@Slf4j
public class AccessFilter extends ZuulFilter {

    //设置过滤器的类型: pre,routing,post,
    @Override
    public String filterType() {
        return FilterConstants.PRE_TYPE;
    }

    //设置过滤器的顺序号
    @Override
    public int filterOrder() {
        return 6;
    }

    @Override
    public boolean shouldFilter() {
        //如果调用item-service要执行过滤代码判断权限
        //否则不执行过滤代码
        //获取调用的服务id
        RequestContext ctx= RequestContext.getCurrentContext();
        String serviceId = (String) ctx.get(FilterConstants.SERVICE_ID_KEY);
        //判断是不是item-service
        return "item-service".equalsIgnoreCase(serviceId);
    }

    //过滤代码
    @Override
    public Object run() throws ZuulException {
       RequestContext ctx = RequestContext.getCurrentContext();
        HttpServletRequest request = ctx.getRequest();

        String token = request.getParameter("token");
        //如果没有收到token参数，认为用户没登录,阻止他继续调用
        if (StringUtils.isBlank(token)){
            //阻止他继续调用
            ctx.setSendZuulResponse(false);//不再向后台服务器转发
            ctx.addZuulRequestHeader("Content-Type", "application/json");
            //JsonResult - {code:401,msg:"not login",data:null}
            ctx.setResponseBody(JsonResult.err().msg("not login").toString());
        }
        return null;//再当前zuul版本中，这个返回值没有任何作用;
    }
}
